<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页 - 记账助手</title>
    <link rel="stylesheet" href="styles.css">
    <link href="js/bootstrap.min.css" rel="stylesheet">
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="screen">
            
            <div class="app-container">
                <div class="header">
                    <div class="greeting" id="greeting">早上好！</div>
                    <div class="date" id="current-date">2024年5月28日 星期三</div>
                </div>
                
                <div class="balance-card">
                    <div class="balance-label">当前余额</div>
                    <div class="balance-amount">¥12,386</div>
                    <div class="balance-stats">
                        <div class="stat">
                            <div class="stat-label">本月收入</div>
                            <div class="stat-value">¥8,500</div>
                        </div>
                        <div class="stat">
                            <div class="stat-label">本月支出</div>
                            <div class="stat-value">¥3,240</div>
                        </div>
                    </div>
                </div>
                
                <!-- 预算概览卡片 - 优化版 -->
                <div class="budget-overview-card-enhanced">
                    <div class="budget-header-enhanced">
                        <div class="budget-title-wrapper">
                            <div class="budget-icon">💰</div>
                            <div class="budget-title-info">
                                <h3 id="budgetPeriodTitle">本月预算</h3>
                                <div class="budget-subtitle" id="budgetSubtitle">智能预算管理</div>
                            </div>
                        </div>
                        <div class="budget-actions">
                            <button class="budget-setting-btn" onclick="openBudgetSettings()">⚙️</button>
                            <a href="budget-management.html" class="budget-manage-btn">管理</a>
                        </div>
                    </div>
                    
                    <!-- 预算周期选择器 - 优化版 -->
                    <div class="period-selector-enhanced">
                        <button class="period-btn-enhanced active" data-period="monthly">
                            <span class="period-label">月度</span>
                            <span class="period-amount" id="monthlyAmount">¥5,000</span>
                        </button>
                        <button class="period-btn-enhanced" data-period="quarterly">
                            <span class="period-label">季度</span>
                            <span class="period-amount" id="quarterlyAmount">¥15,000</span>
                        </button>
                        <button class="period-btn-enhanced" data-period="yearly">
                            <span class="period-label">年度</span>
                            <span class="period-amount" id="yearlyAmount">¥60,000</span>
                        </button>
                    </div>
                    
                    <!-- 智能提醒系统 - 优化版 -->
                    <div class="smart-alert-system" id="smartAlertSystem">
                        <!-- 动态生成智能提醒 -->
                    </div>
                    
                    <!-- 预算进度展示 - 优化版 -->
                    <div class="budget-progress-enhanced">
                        <div class="progress-header">
                            <div class="progress-info">
                                <span class="used-amount" id="usedAmount">¥3,240</span>
                                <span class="total-amount" id="totalAmount">/ ¥5,000</span>
                            </div>
                            <div class="progress-percentage" id="progressPercentage">65%</div>
                        </div>
                        <div class="progress-bar-enhanced">
                            <div class="progress-fill" id="progressFill" style="width: 65%"></div>
                            <div class="progress-markers">
                                <div class="marker" style="left: 50%"></div>
                                <div class="marker" style="left: 80%"></div>
                            </div>
                        </div>
                        <div class="progress-labels">
                            <span class="label-start">¥0</span>
                            <span class="label-middle">¥2,500</span>
                            <span class="label-end">¥5,000</span>
                        </div>
                    </div>
                    
                    <!-- 预算洞察分析 - 优化版 -->
                    <div class="budget-insights-enhanced">
                        <div class="insights-grid">
                            <div class="insight-card">
                                <div class="insight-icon">📊</div>
                                <div class="insight-content">
                                    <div class="insight-value" id="dailyAverageEnhanced">¥108</div>
                                    <div class="insight-label">日均支出</div>
                                    <div class="insight-trend" id="dailyTrend">↓ 比昨日少12%</div>
                                </div>
                            </div>
                            <div class="insight-card">
                                <div class="insight-icon">🎯</div>
                                <div class="insight-content">
                                    <div class="insight-value" id="projectedBalanceEnhanced">¥420</div>
                                    <div class="insight-label">预计结余</div>
                                    <div class="insight-trend" id="balanceTrend">↑ 超出预期8%</div>
                                </div>
                            </div>
                            <div class="insight-card">
                                <div class="insight-icon">⏰</div>
                                <div class="insight-content">
                                    <div class="insight-value" id="remainingDays">12天</div>
                                    <div class="insight-label">剩余天数</div>
                                    <div class="insight-trend" id="daysTrend">建议日均¥147</div>
                                </div>
                            </div>
                            <div class="insight-card">
                                <div class="insight-icon">🏆</div>
                                <div class="insight-content">
                                    <div class="insight-value" id="budgetScore">85分</div>
                                    <div class="insight-label">预算评分</div>
                                    <div class="insight-trend" id="scoreTrend">表现良好</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 分类预算概览 - 优化版 -->
                    <div class="category-budget-overview" id="categoryBudgetOverview">
                        <div class="category-header">
                            <span class="category-title">分类预算</span>
                            <button class="category-expand-btn" id="categoryExpandBtn" onclick="toggleCategoryDetails()">展开 ▼</button>
                        </div>
                        <div class="category-summary" id="categorySummary">
                            <!-- 动态生成分类预算摘要 -->
                        </div>
                        <div class="category-details" id="categoryDetails" style="display: none;">
                            <!-- 动态生成详细分类预算 -->
                        </div>
                    </div>
                    
                    <!-- 智能建议和快速操作 - 优化版 -->
                    <div class="budget-actions-enhanced">
                        <div class="smart-suggestions" id="smartSuggestions">
                            <!-- 动态生成智能建议 -->
                        </div>
                        <div class="quick-actions-grid">
                            <button class="quick-action-enhanced" onclick="showBudgetTemplates()">
                                <div class="action-icon">📋</div>
                                <div class="action-text">
                                    <div class="action-title">预算模板</div>
                                    <div class="action-desc">快速应用</div>
                                </div>
                            </button>
                            <button class="quick-action-enhanced" onclick="showBudgetAdjust()">
                                <div class="action-icon">⚙️</div>
                                <div class="action-text">
                                    <div class="action-title">智能调整</div>
                                    <div class="action-desc">优化预算</div>
                                </div>
                            </button>
                            <button class="quick-action-enhanced" onclick="showBudgetAnalysis()">
                                <div class="action-icon">📊</div>
                                <div class="action-text">
                                    <div class="action-title">消费分析</div>
                                    <div class="action-desc">深度洞察</div>
                                </div>
                            </button>
                            <button class="quick-action-enhanced" onclick="showBudgetGoals()">
                                <div class="action-icon">🎯</div>
                                <div class="action-text">
                                    <div class="action-title">目标设定</div>
                                    <div class="action-desc">制定计划</div>
                                </div>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="quick-actions">
                    <div class="section-title">快速记账</div>
                    <div class="action-buttons">
                        <button class="action-btn" id="expense-btn">
                            <div class="action-icon expense-icon">-</div>
                            <div class="action-text">记支出</div>
                        </button>
                        <button class="action-btn" id="income-btn">
                            <div class="action-icon income-icon">+</div>
                            <div class="action-text">记收入</div>
                        </button>
                    </div>
                </div>
                
                <div class="recent-transactions">
                    <div class="section-title">最近交易</div>
                    
                    <div class="transaction-item">
                        <div class="item-user-avatar">张</div>
                        <div class="transaction-icon food-icon">🍔</div>
                        <div class="transaction-info">
                            <h4>餐饮·午餐</h4>
                        </div>
                        <div class="transaction-amount expense-amount">-¥45</div>
                        <button class="transaction-options">⋯</button>
                    </div>
                    
                    <div class="transaction-item">
                        <div class="item-user-avatar">李</div>
                        <div class="transaction-icon transport-icon">🚇</div>
                        <div class="transaction-info">
                            <h4>交通·地铁出行</h4>
                        </div>
                        <div class="transaction-amount expense-amount">-¥6</div>
                        <button class="transaction-options">⋯</button>
                    </div>
                    
                    <div class="transaction-item">
                        <div class="item-user-avatar">王</div>
                        <div class="transaction-icon salary-icon">💰</div>
                        <div class="transaction-info">
                            <h4>工资·月薪收入</h4>
                        </div>
                        <div class="transaction-amount income-amount">+¥8,500</div>
                        <button class="transaction-options">⋯</button>
                    </div>
                </div>
            </div>
            
            <div class="bottom-nav">
                <div class="nav-item active" data-page="index.html">
                    <div class="nav-icon">🏠</div>
                    <div>首页</div>
                </div>
                <div class="nav-item" data-page="statistics.html">
                    <div class="nav-icon">📊</div>
                    <div>统计</div>
                </div>
                <div class="nav-item" id="quick-record-btn">
                    <div class="nav-icon" style="font-size: 24px;">➕</div>
                    <div>记账</div>
                </div>
                <div class="nav-item" data-page="details.html">
                    <div class="nav-icon">📝</div>
                    <div>明细</div>
                </div>
                <div class="nav-item" data-page="user.html">
                    <div class="nav-icon">👤</div>
                    <div>我的</div>
                </div>
            </div>
        </div>
        
        <!-- 快速记录模态框 -->
        <div class="modal fade" id="quickRecordModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">快速记账</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="form-label">文字输入</label>
                            <div class="input-group mb-3">
                                <input type="text" class="form-input" id="quickText" placeholder="例如：午餐 25元">
                                <button class="btn btn-outline-secondary" type="button" id="voiceInputBtn">🎤</button>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">图片上传</label>
                            <div class="image-upload-container">
                                <div class="image-preview" id="imagePreview">
                                    <div class="upload-placeholder" id="uploadPlaceholder">
                                        <div class="upload-icon">📷</div>
                                        <div class="upload-text">点击上传图片</div>
                                    </div>
                                    <img id="previewImage" style="display: none; width: 100%; height: 100%; object-fit: cover;">
                                </div>
                                <div class="image-actions" id="imageActions" style="display: none;">
                                    <button class="btn btn-sm btn-danger" id="removeImageBtn">删除</button>
                                    <button class="btn btn-sm btn-primary" id="recognizeBtn">识别</button>
                                </div>
                                <input type="file" id="imageInput" accept="image/*" style="display: none;">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="submitQuickRecord">提交</button>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
            // 更新时间和日期
            function updateDateTime() {
                const now = new Date();
                const hours = now.getHours();
                let greeting = "";
                
                if (hours < 12) {
                    greeting = "早上好！";
                } else if (hours < 18) {
                    greeting = "下午好！";
                } else {
                    greeting = "晚上好！";
                }
                
                document.getElementById('greeting').textContent = greeting;
                
                const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
                const dateStr = now.toLocaleDateString('zh-CN', options);
                document.getElementById('current-date').textContent = dateStr;
            }
            
            updateDateTime();
            
            // 导航点击事件
            document.querySelectorAll('.nav-item').forEach(item => {
                if (item.id !== 'quick-record-btn') {
                    item.addEventListener('click', function() {
                        const page = this.getAttribute('data-page');
                        if (page) {
                            window.location.href = page;
                        }
                    });
                }
            });
            
            // 快速记录功能
            const quickRecordBtn = document.getElementById('quick-record-btn');
            const quickRecordModal = new bootstrap.Modal(document.getElementById('quickRecordModal'));
            
            quickRecordBtn.addEventListener('click', function() {
                quickRecordModal.show();
            });
            
            // 语音输入模拟
            document.getElementById('voiceInputBtn').addEventListener('click', function() {
                // 模拟语音识别中
                this.textContent = '🔴';
                this.disabled = true;
                
                // 模拟2秒后识别完成
                setTimeout(() => {
                    document.getElementById('quickText').value = '午餐 35元';
                    this.textContent = '🎤';
                    this.disabled = false;
                }, 2000);
            });
            
            // 图片上传和预览
            const imagePreview = document.getElementById('imagePreview');
            const uploadPlaceholder = document.getElementById('uploadPlaceholder');
            const previewImage = document.getElementById('previewImage');
            const imageInput = document.getElementById('imageInput');
            const imageActions = document.getElementById('imageActions');
            const removeImageBtn = document.getElementById('removeImageBtn');
            const recognizeBtn = document.getElementById('recognizeBtn');
            
            imagePreview.addEventListener('click', function() {
                if (previewImage.style.display === 'none') {
                    imageInput.click();
                }
            });
            
            imageInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    const file = this.files[0];
                    
                    // 验证文件类型
                    if (!file.type.match('image.*')) {
                        alert('请选择图片文件');
                        return;
                    }
                    
                    // 验证文件大小（最大5MB）
                    if (file.size > 5 * 1024 * 1024) {
                        alert('图片大小不能超过5MB');
                        return;
                    }
                    
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        previewImage.src = e.target.result;
                        previewImage.style.display = 'block';
                        uploadPlaceholder.style.display = 'none';
                        imageActions.style.display = 'flex';
                    };
                    
                    reader.readAsDataURL(file);
                }
            });
            
            removeImageBtn.addEventListener('click', function() {
                previewImage.src = '';
                previewImage.style.display = 'none';
                uploadPlaceholder.style.display = 'flex';
                imageActions.style.display = 'none';
                imageInput.value = '';
            });
            
            recognizeBtn.addEventListener('click', function() {
                // 模拟图像识别中
                this.textContent = '识别中...';
                this.disabled = true;
                
                // 模拟2秒后识别完成
                setTimeout(() => {
                    document.getElementById('quickText').value = '超市购物 89.5元';
                    this.textContent = '识别';
                    this.disabled = false;
                }, 2000);
            });
            
            // 提交快速记录
            document.getElementById('submitQuickRecord').addEventListener('click', function() {
                const text = document.getElementById('quickText').value.trim();
                
                if (text) {
                    // 简单解析文本
                    if (text.includes('元')) {
                        const parts = text.split(' ');
                        if (parts.length >= 2) {
                            const category = parts[0];
                            const amountText = parts[1].replace('元', '');
                            const amount = parseFloat(amountText);
                            
                            if (!isNaN(amount)) {
                                // 根据金额正负判断收入或支出
                                if (amount < 0) {
                                    window.location.href = `income-record.html?category=${category}&amount=${Math.abs(amount)}`;
                                } else {
                                    window.location.href = `expense-record.html?category=${category}&amount=${amount}`;
                                }
                                return;
                            }
                        }
                    }
                    
                    // 默认跳转到支出记录页面
                    window.location.href = 'expense-record.html';
                } else {
                    alert('请输入记账内容');
                }
            });
            
            // 全局变量
            let currentBudgetPeriod = 'monthly';
            let budgetData = {
                monthly: { total: 5000, used: 3240 },
                quarterly: { total: 15000, used: 9720 },
                yearly: { total: 60000, used: 38880 }
            };
            
            // 初始化预算概览 - 优化版
            function initBudgetOverview() {
                // 从本地存储获取预算数据
                const budgetData = JSON.parse(localStorage.getItem('budgetData')) || {
                    monthly: { total: 5000, used: 3240 },
                    quarterly: { total: 15000, used: 8500 },
                    yearly: { total: 60000, used: 28000 }
                };
                
                // 更新全局预算数据
                window.budgetData = budgetData;
                
                // 初始化所有组件
                initPeriodSelectorEnhanced();
                initSmartAlertSystem();
                initBudgetProgressEnhanced();
                initBudgetInsightsEnhanced();
                initCategoryBudgetOverview();
                initSmartSuggestions();
                initQuickActionsEnhanced();
                
                // 更新显示
                updateBudgetDisplay();
            }
            
            // 初始化优化版周期选择器
            function initPeriodSelectorEnhanced() {
                const periodBtns = document.querySelectorAll('.period-btn-enhanced');
                
                periodBtns.forEach(btn => {
                    btn.addEventListener('click', function() {
                        // 移除所有活动状态
                        periodBtns.forEach(b => b.classList.remove('active'));
                        // 添加当前活动状态
                        this.classList.add('active');
                        
                        // 更新当前周期
                        currentBudgetPeriod = this.dataset.period;
                        
                        // 更新显示
                         updateBudgetDisplay();
                         updateSmartAlerts();
                         updateBudgetInsights();
                         updateCategoryDisplay();
                    });
                });
            }
            
            // 初始化智能提醒系统
             function initSmartAlertSystem() {
                 updateSmartAlerts();
             }
            
            // 更新智能提醒
             function updateSmartAlerts() {
                const alertSystem = document.getElementById('smartAlertSystem');
                const currentData = budgetData[currentBudgetPeriod];
                const usagePercentage = (currentData.used / currentData.total) * 100;
                
                let alerts = [];
                
                // 根据使用百分比生成不同类型的提醒
                if (usagePercentage >= 90) {
                    alerts.push({
                        type: 'danger',
                        icon: '🚨',
                        text: `预算即将超支！已使用${usagePercentage.toFixed(0)}%，建议立即调整支出计划。`
                    });
                } else if (usagePercentage >= 75) {
                    alerts.push({
                        type: 'warning',
                        icon: '⚠️',
                        text: `预算使用已达${usagePercentage.toFixed(0)}%，请注意控制支出。`
                    });
                } else if (usagePercentage <= 30) {
                    alerts.push({
                        type: 'success',
                        icon: '✅',
                        text: `预算控制良好！当前使用${usagePercentage.toFixed(0)}%，继续保持。`
                    });
                }
                
                // 添加智能建议
                const remainingDays = getRemainingDays();
                const dailyBudget = (currentData.total - currentData.used) / remainingDays;
                
                if (dailyBudget > 0) {
                    alerts.push({
                        type: 'info',
                        icon: '💡',
                        text: `剩余${remainingDays}天，建议日均支出不超过¥${dailyBudget.toFixed(0)}。`
                    });
                }
                
                // 渲染提醒
                alertSystem.innerHTML = alerts.map(alert => `
                    <div class="smart-alert-item ${alert.type}">
                        <div class="smart-alert-icon">${alert.icon}</div>
                        <div class="smart-alert-text">${alert.text}</div>
                    </div>
                `).join('');
            }
            
            // 初始化优化版预算进度
             function initBudgetProgressEnhanced() {
                 updateBudgetProgress();
             }
            
            // 更新预算进度
             function updateBudgetProgress() {
                const currentData = budgetData[currentBudgetPeriod];
                const usagePercentage = (currentData.used / currentData.total) * 100;
                
                // 更新金额显示
                document.getElementById('usedAmount').textContent = `¥${currentData.used.toLocaleString()}`;
                document.getElementById('totalAmount').textContent = `/ ¥${currentData.total.toLocaleString()}`;
                document.getElementById('progressPercentage').textContent = `${usagePercentage.toFixed(0)}%`;
                
                // 更新进度条
                const progressFill = document.getElementById('progressFill');
                progressFill.style.width = `${Math.min(usagePercentage, 100)}%`;
                
                // 根据使用情况改变进度条颜色
                if (usagePercentage >= 90) {
                    progressFill.style.background = 'linear-gradient(90deg, #ff6b6b 0%, #ee5a52 100%)';
                } else if (usagePercentage >= 75) {
                    progressFill.style.background = 'linear-gradient(90deg, #feca57 0%, #ff9ff3 100%)';
                } else {
                    progressFill.style.background = 'linear-gradient(90deg, #4facfe 0%, #00f2fe 100%)';
                }
            }
            
            // 初始化优化版预算洞察
             function initBudgetInsightsEnhanced() {
                 updateBudgetInsights();
             }
            
            // 更新预算洞察
             function updateBudgetInsights() {
                const currentData = budgetData[currentBudgetPeriod];
                const remainingDays = getRemainingDays();
                const dailyAverage = currentData.used / (getDaysInPeriod() - remainingDays);
                const projectedBalance = currentData.total - (dailyAverage * getDaysInPeriod());
                const budgetScore = calculateBudgetScore(currentData);
                
                // 更新洞察数据
                document.getElementById('dailyAverageEnhanced').textContent = `¥${dailyAverage.toFixed(0)}`;
                document.getElementById('projectedBalanceEnhanced').textContent = `¥${projectedBalance.toFixed(0)}`;
                document.getElementById('remainingDays').textContent = `${remainingDays}天`;
                document.getElementById('budgetScore').textContent = `${budgetScore}分`;
                
                // 更新趋势信息
                document.getElementById('dailyTrend').textContent = dailyAverage > 100 ? '↑ 支出偏高' : '↓ 控制良好';
                document.getElementById('balanceTrend').textContent = projectedBalance > 0 ? '↑ 有结余' : '↓ 可能超支';
                document.getElementById('daysTrend').textContent = `建议日均¥${((currentData.total - currentData.used) / remainingDays).toFixed(0)}`;
                document.getElementById('scoreTrend').textContent = budgetScore >= 80 ? '表现优秀' : budgetScore >= 60 ? '表现良好' : '需要改进';
            }
            
            // 初始化分类预算概览
            function initCategoryBudgetOverview() {
                updateCategoryDisplay();
            }
            
            // 更新分类显示
            function updateCategoryDisplay() {
                const categorySummary = document.getElementById('categorySummary');
                const categoryDetails = document.getElementById('categoryDetails');
                
                // 模拟分类数据
                const categories = [
                    { name: '餐饮', icon: '🍔', used: 800, total: 1500, color: '#ff6b6b' },
                    { name: '交通', icon: '🚗', used: 300, total: 500, color: '#4ecdc4' },
                    { name: '购物', icon: '🛍️', used: 600, total: 1000, color: '#45b7d1' },
                    { name: '娱乐', icon: '🎬', used: 200, total: 400, color: '#96ceb4' },
                    { name: '其他', icon: '📦', used: 150, total: 300, color: '#feca57' }
                ];
                
                // 生成摘要
                categorySummary.innerHTML = categories.map(cat => {
                    const percentage = (cat.used / cat.total) * 100;
                    return `<div class="category-summary-item">${cat.icon} ${cat.name} ${percentage.toFixed(0)}%</div>`;
                }).join('');
                
                // 生成详细信息
                categoryDetails.innerHTML = categories.map(cat => {
                    const percentage = (cat.used / cat.total) * 100;
                    return `
                        <div class="category-detail-item">
                            <div class="category-detail-icon">${cat.icon}</div>
                            <div class="category-detail-info">
                                <div class="category-detail-name">${cat.name}</div>
                                <div class="category-detail-progress">¥${cat.used} / ¥${cat.total} (${percentage.toFixed(0)}%)</div>
                            </div>
                            <div class="category-detail-amount">¥${cat.total - cat.used}</div>
                        </div>
                    `;
                }).join('');
            }
            
            // 初始化智能建议
            function initSmartSuggestions() {
                const suggestions = document.getElementById('smartSuggestions');
                
                const suggestionList = [
                    { icon: '💡', text: '本月餐饮支出较高，建议多在家用餐' },
                    { icon: '🎯', text: '交通费用控制良好，继续保持' },
                    { icon: '📊', text: '建议设置每日支出提醒，避免超支' }
                ];
                
                suggestions.innerHTML = suggestionList.map(suggestion => `
                    <div class="suggestion-item">
                        <div class="suggestion-icon">${suggestion.icon}</div>
                        <div class="suggestion-text">${suggestion.text}</div>
                    </div>
                `).join('');
            }
            
            // 初始化优化版快速操作
            function initQuickActionsEnhanced() {
                // 快速操作按钮已在HTML中定义，这里可以添加额外的事件监听
            }
            
            // 更新预算显示
            function updateBudgetDisplay() {
                const currentData = budgetData[currentBudgetPeriod];
                
                // 更新标题
                const titles = {
                    monthly: '本月预算',
                    quarterly: '本季预算', 
                    yearly: '本年预算'
                };
                document.getElementById('budgetPeriodTitle').textContent = titles[currentBudgetPeriod];
                
                // 更新周期金额显示
                document.getElementById('monthlyAmount').textContent = `¥${budgetData.monthly.total.toLocaleString()}`;
                document.getElementById('quarterlyAmount').textContent = `¥${budgetData.quarterly.total.toLocaleString()}`;
                document.getElementById('yearlyAmount').textContent = `¥${budgetData.yearly.total.toLocaleString()}`;
                
                // 更新进度
                 updateBudgetProgress();
            }
            
            // 辅助函数
            function getRemainingDays() {
                const now = new Date();
                if (currentBudgetPeriod === 'monthly') {
                    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
                    return lastDay.getDate() - now.getDate();
                } else if (currentBudgetPeriod === 'quarterly') {
                    const quarter = Math.floor(now.getMonth() / 3);
                    const lastMonth = (quarter + 1) * 3 - 1;
                    const lastDay = new Date(now.getFullYear(), lastMonth + 1, 0);
                    return Math.ceil((lastDay - now) / (1000 * 60 * 60 * 24));
                } else {
                    const lastDay = new Date(now.getFullYear() + 1, 0, 0);
                    return Math.ceil((lastDay - now) / (1000 * 60 * 60 * 24));
                }
            }
            
            function getDaysInPeriod() {
                const now = new Date();
                if (currentBudgetPeriod === 'monthly') {
                    return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
                } else if (currentBudgetPeriod === 'quarterly') {
                    return 90; // 大约
                } else {
                    return 365;
                }
            }
            
            function calculateBudgetScore(data) {
                const usagePercentage = (data.used / data.total) * 100;
                if (usagePercentage <= 70) return 90 + Math.random() * 10;
                if (usagePercentage <= 85) return 70 + Math.random() * 20;
                return 50 + Math.random() * 20;
            }
            
            // 切换分类详情显示
            function toggleCategoryDetails() {
                const details = document.getElementById('categoryDetails');
                const btn = document.getElementById('categoryExpandBtn');
                
                if (details.style.display === 'none') {
                    details.style.display = 'block';
                    btn.textContent = '收起 ▲';
                } else {
                    details.style.display = 'none';
                    btn.textContent = '展开 ▼';
                }
            }
            
            // 预算设置
            function openBudgetSettings() {
                alert('预算设置功能开发中...');
            }
            
            // 预算模板
            function showBudgetTemplates() {
                alert('预算模板功能开发中...');
            }
            
            // 预算调整
            function showBudgetAdjust() {
                alert('预算调整功能开发中...');
            }
            
            // 预算分析
            function showBudgetAnalysis() {
                alert('预算分析功能开发中...');
            }
            
            // 预算目标设定
            function showBudgetGoals() {
                alert('预算目标设定功能开发中...');
            }
            
            // 更新预算概览
            function updateBudgetOverview(totalBudget, totalUsed) {
                const remaining = totalBudget - totalUsed;
                const percentage = Math.min(Math.round((totalUsed / totalBudget) * 100), 100);
                
                // 更新进度条和文本
                const progressBar = document.querySelector('.budget-overview-card .progress-bar');
                const progressLabels = document.querySelectorAll('.budget-overview-card .progress-label span');
                
                progressBar.style.width = `${percentage}%`;
                progressLabels[0].textContent = `已使用：¥${totalUsed.toLocaleString()} / ¥${totalBudget.toLocaleString()}`;
                progressLabels[1].textContent = `剩余：¥${remaining.toLocaleString()}`;
                
                // 根据使用比例设置进度条颜色
                if (percentage < 70) {
                    progressBar.className = 'progress-bar progress-normal';
                } else if (percentage < 90) {
                    progressBar.className = 'progress-bar progress-warning';
                } else {
                    progressBar.className = 'progress-bar progress-danger';
                }
            }
            
            // 更新分类预算
            function updateCategoryBudgets(categoryBudgets) {
                const container = document.querySelector('.budget-categories-mini');
                container.innerHTML = ''; // 清空现有内容
                
                // 获取前两个分类（如果有多个）
                const categories = Object.values(categoryBudgets).slice(0, 2);
                
                categories.forEach(category => {
                    const percentage = Math.min(Math.round((category.used / category.budget) * 100), 100);
                    
                    const categoryItem = document.createElement('div');
                    categoryItem.className = 'category-budget-item';
                    categoryItem.innerHTML = `
                        <div class="category-budget-info">
                            <span class="category-icon">${category.icon}</span>
                            <span class="category-name">${category.name}</span>
                            <span class="category-amount">¥${category.used.toLocaleString()}/${category.budget.toLocaleString()}</span>
                        </div>
                        <div class="category-progress-bar">
                            <div class="category-progress" style="width: ${percentage}%"></div>
                        </div>
                    `;
                    
                    container.appendChild(categoryItem);
                });
            }
            
            // 获取分类图标
            function getCategoryIcon(category) {
                const icons = {
                    '餐饮': '🍔',
                    '交通': '🚗',
                    '购物': '🛍️',
                    '娱乐': '🎮',
                    '居家': '🏠',
                    '通讯': '📱',
                    '服饰': '👔',
                    '美容': '💄',
                    '运动': '⚽',
                    '旅行': '✈️',
                    '医疗': '💊',
                    '教育': '📚',
                    '金融': '💰',
                    '人情': '🎁',
                    '其他': '📝'
                };
                
                return icons[category] || '📝';
            }
            
            // 获取分类名称
            function getCategoryName(categoryKey) {
                const categoryNames = {
                    'food': '餐饮',
                    'transport': '交通',
                    'shopping': '购物',
                    'entertainment': '娱乐',
                    'medical': '医疗',
                    'education': '教育',
                    'home': '居家',
                    'communication': '通讯',
                    'clothes': '服饰',
                    'beauty': '美容',
                    'sports': '运动',
                    'travel': '旅行',
                    'finance': '金融',
                    'social': '人情',
                    'other': '其他'
                };
                
                return categoryNames[categoryKey] || '其他';
            }
            
            // 初始化周期切换器
            function initPeriodSwitcher() {
                const periodBtns = document.querySelectorAll('.period-btn');
                
                periodBtns.forEach(btn => {
                    btn.addEventListener('click', function() {
                        // 移除所有活动状态
                        periodBtns.forEach(b => b.classList.remove('active'));
                        // 添加当前按钮的活动状态
                        this.classList.add('active');
                        
                        // 更新当前周期
                        currentBudgetPeriod = this.dataset.period;
                        
                        // 更新预算显示
                        const totalBudget = budgetData[currentBudgetPeriod].total;
                        const totalUsed = budgetData[currentBudgetPeriod].used;
                        updateBudgetOverview(totalBudget, totalUsed);
                        
                        // 更新洞察数据
                        updateBudgetInsights();
                        
                        // 更新智能提醒
                        updateSmartAlerts();
                        
                        // 更新动态类别预算
                        updateDynamicCategoryBudgets();
                    });
                });
            }
            
            // 初始化智能提醒
            function initSmartAlerts() {
                updateSmartAlerts();
            }
            
            // 更新智能提醒
            function updateSmartAlerts() {
                const alertsContainer = document.querySelector('.smart-alerts');
                const data = budgetData[currentBudgetPeriod];
                const percentage = (data.used / data.total) * 100;
                
                let alerts = [];
                
                if (percentage >= 100) {
                    alerts.push({
                        type: 'danger',
                        icon: '⚠️',
                        text: `${getPeriodName()}预算已超支 ¥${(data.used - data.total).toLocaleString()}`
                    });
                } else if (percentage >= 80) {
                    alerts.push({
                        type: 'warning',
                        icon: '⚡',
                        text: `${getPeriodName()}预算已使用${Math.round(percentage)}%，请注意控制支出`
                    });
                } else if (percentage < 50) {
                    alerts.push({
                        type: 'success',
                        icon: '✅',
                        text: `${getPeriodName()}预算控制良好，还可支出 ¥${(data.total - data.used).toLocaleString()}`
                    });
                }
                
                // 添加智能建议
                if (currentBudgetPeriod === 'monthly') {
                    const daysInMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
                    const currentDay = new Date().getDate();
                    const remainingDays = daysInMonth - currentDay;
                    const dailyAverage = data.used / currentDay;
                    const projectedTotal = dailyAverage * daysInMonth;
                    
                    if (projectedTotal > data.total * 1.1) {
                        alerts.push({
                            type: 'warning',
                            icon: '📊',
                            text: `按当前消费速度，本月预计超支 ¥${Math.round(projectedTotal - data.total)}`
                        });
                    }
                }
                
                alertsContainer.innerHTML = alerts.map(alert => `
                    <div class="alert-item ${alert.type}">
                        <span class="alert-icon">${alert.icon}</span>
                        <span class="alert-text">${alert.text}</span>
                    </div>
                `).join('');
            }
            
            // 初始化预算洞察
            function initBudgetInsights() {
                updateBudgetInsights();
            }
            
            // 更新预算洞察
            function updateBudgetInsights() {
                const data = budgetData[currentBudgetPeriod];
                const remaining = data.total - data.used;
                
                let dailyAverage, projectedBalance;
                
                if (currentBudgetPeriod === 'monthly') {
                    const currentDay = new Date().getDate();
                    dailyAverage = Math.round(data.used / currentDay);
                    const daysInMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
                    const remainingDays = daysInMonth - currentDay;
                    projectedBalance = remaining - (dailyAverage * remainingDays);
                } else if (currentBudgetPeriod === 'quarterly') {
                    const quarterStart = new Date(new Date().getFullYear(), Math.floor(new Date().getMonth() / 3) * 3, 1);
                    const daysPassed = Math.ceil((new Date() - quarterStart) / (1000 * 60 * 60 * 24));
                    dailyAverage = Math.round(data.used / daysPassed);
                    const quarterEnd = new Date(quarterStart.getFullYear(), quarterStart.getMonth() + 3, 0);
                    const remainingDays = Math.ceil((quarterEnd - new Date()) / (1000 * 60 * 60 * 24));
                    projectedBalance = remaining - (dailyAverage * remainingDays);
                } else {
                    const yearStart = new Date(new Date().getFullYear(), 0, 1);
                    const daysPassed = Math.ceil((new Date() - yearStart) / (1000 * 60 * 60 * 24));
                    dailyAverage = Math.round(data.used / daysPassed);
                    const yearEnd = new Date(new Date().getFullYear(), 11, 31);
                    const remainingDays = Math.ceil((yearEnd - new Date()) / (1000 * 60 * 60 * 24));
                    projectedBalance = remaining - (dailyAverage * remainingDays);
                }
                
                const insightsContainer = document.querySelector('.budget-insights');
                insightsContainer.innerHTML = `
                    <div class="insight-item">
                        <div class="insight-value">¥${dailyAverage.toLocaleString()}</div>
                        <div class="insight-label">日均消费</div>
                    </div>
                    <div class="insight-item">
                        <div class="insight-value ${projectedBalance >= 0 ? '' : 'text-danger'}">¥${projectedBalance.toLocaleString()}</div>
                        <div class="insight-label">预计结余</div>
                    </div>
                `;
            }
            
            // 初始化快速操作
            function initQuickActions() {
                const quickActionBtns = document.querySelectorAll('.quick-action-btn');
                
                quickActionBtns.forEach(btn => {
                    btn.addEventListener('click', function() {
                        const action = this.dataset.action;
                        
                        switch(action) {
                            case 'template':
                                // 跳转到预算管理页面的模板选择
                                window.location.href = 'budget-management.html#templates';
                                break;
                            case 'adjust':
                                // 跳转到预算管理页面的快速调整
                                window.location.href = 'budget-management.html#adjust';
                                break;
                            case 'analysis':
                                // 跳转到预算管理页面的消费分析
                                window.location.href = 'budget-management.html#analysis';
                                break;
                        }
                    });
                });
            }
            
            // 获取周期名称
            function getPeriodName() {
                const names = {
                    'monthly': '本月',
                    'quarterly': '本季度',
                    'yearly': '本年度'
                };
                return names[currentBudgetPeriod] || '本月';
            }
            
            // 更新动态类别预算项
            function updateDynamicCategoryBudgets() {
                const container = document.querySelector('.budget-categories-dynamic');
                
                // 模拟分类预算数据
                const categoryData = {
                    'monthly': [
                        { name: '餐饮', icon: '🍔', budget: 2000, used: 1200, status: 'normal' },
                        { name: '交通', icon: '🚗', budget: 1000, used: 800, status: 'warning' },
                        { name: '购物', icon: '🛍️', budget: 1500, used: 1600, status: 'danger' }
                    ],
                    'quarterly': [
                        { name: '餐饮', icon: '🍔', budget: 6000, used: 3600, status: 'normal' },
                        { name: '交通', icon: '🚗', budget: 3000, used: 2400, status: 'warning' },
                        { name: '购物', icon: '🛍️', budget: 4500, used: 4800, status: 'danger' }
                    ],
                    'yearly': [
                        { name: '餐饮', icon: '🍔', budget: 24000, used: 14400, status: 'normal' },
                        { name: '交通', icon: '🚗', budget: 12000, used: 9600, status: 'warning' },
                        { name: '购物', icon: '🛍️', budget: 18000, used: 19200, status: 'danger' }
                    ]
                };
                
                const categories = categoryData[currentBudgetPeriod] || [];
                
                container.innerHTML = categories.map(category => {
                    const percentage = Math.min(Math.round((category.used / category.budget) * 100), 100);
                    
                    return `
                        <div class="category-budget-item-enhanced">
                            <div class="category-header">
                                <div class="category-left">
                                    <div class="category-status ${category.status}"></div>
                                    <span class="category-icon">${category.icon}</span>
                                    <span class="category-name">${category.name}</span>
                                </div>
                                <div class="category-right">
                                    <span class="category-percentage ${category.status}">${percentage}%</span>
                                </div>
                            </div>
                            <div class="category-progress-bar">
                                <div class="category-progress" style="width: ${percentage}%"></div>
                            </div>
                            <div class="category-amount">¥${category.used.toLocaleString()} / ¥${category.budget.toLocaleString()}</div>
                        </div>
                    `;
                }).join('');
            }
            
            // 页面加载时初始化预算概览
            document.addEventListener('DOMContentLoaded', function() {
                initBudgetOverview();
                updateDynamicCategoryBudgets();
            });
        </script>
    </body>
</html>